package no06;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/4/24 15:09
 * 从尾到头打印链表
 * https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
 */
public class Solution {
    static class ListNode {
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }

    // 方法一: 递归
    public int[] reversePrint01(ListNode head) {
        List<Integer> res = new ArrayList<>();
        reverse(head, res);
        int length = res.size();
        int[] myArray = new int[length];
        int i = 0;
        for(Integer item : res) {
            myArray[i++] = item;
        }
        return myArray;
    }

    public void reverse(ListNode head, List<Integer> res) {
        if (head == null) {
            return;
        }
        reverse(head.next, res);
        res.add(head.val);
    }

    // 方法二: 逆置数组
    public int[] reversePrint02(ListNode head) {
        int count = 0;
        ListNode cur = head;
        // 先统计节点个数, 便于创建数组
        while(cur != null) {
            count++;
            cur = cur.next;
        }
        int[] ret = new int[count];
        cur = head;
        // 再次遍历, 从数组尾部开始存
        for(int i = count - 1; i >= 0; i--) {
            ret[i] = cur.val;
            cur = cur.next;
        }
        return ret;
    }
}
